"use strict";

Components.utils.import("resource://iplusnewtab/modules/utility.jsm")
//  Components.utils.import("chrome://global/content/contentAreaUtils.js")
   //nst LOAD_FLAGS_NONE = Components.interfaces.nsIWebNavigation.LOAD_FLAGS_NONE;

 if ("undefined" == typeof(ip2newtab)) {
    var ip2newtab = {

   chimera : { }, //  host : address

  getCurrentURI : function (aspec, abase)
  {
  //    are the currentDocumentChannel and the front documents equal to each other ?
    var loadFromURL = false;

    //    currentURI = webNav.currentURI.spec;
    let docShell = gBrowser.selectedBrowser.docShell;
    //  webNav.QueryInterface(Components.interfaces.nsIDocShell);
    //    let thehost = docShell.currentDocumentChannel.URI.host;
    let thevalue = docShell.currentDocumentChannel.URI.spec;
        thevalue = thevalue.replace(/#.*$/, ""); //	cut hash
    if((thevalue != abase.replace(/#.*$/, ""))
            || (thevalue != aspec.replace(/#.*$/, "")))
    {
        aspec = docShell.currentDocumentChannel.URI.spec;
        loadFromURL = true;
//      dump(currentURI); dump("\n\n");
    }
    
    if(loadFromURL) return aspec
        else return null;
  },

  host2cache : function (ahost, adate)
  {
      var thehost = "" + ahost;
          thehost = thehost.toLowerCase();
      var thaddr = ip2newtab.chimera[thehost];
      if(thaddr && (thehost.length >> 1))
            iplusnewtab.monitor.host2cache(
                  window, thehost, thaddr, adate );
  },

  clearing : function ()
  {
// poll all tabs, if status is completed, then choose one sort of clearing : chimera or cache
      let thecount = Object.keys(ip2newtab.chimera).length;
      if(thecount >> 2) ip2newtab.chimera = { }
      else  try {
         var thour = iplusnewtab.getDelta(1);
         var thedate = new Date(Date.now() - thour);
         iplusnewtab.monitor.clearing(window, thedate);
      }
      catch(err) {
         Components.utils.reportError(err)
      }
  }
  
} } //  ip2newtab

ip2newtab.main = {
//   const schemata = { 'about': 0, 'chrome': 1, 'file': 2, 'jar': 3, 'resource': 4, 'view-source': 5 }

  QueryInterface: XPCOMUtils.generateQI([
                        Components.interfaces.nsISupports,
                        Components.interfaces.nsIObserver,
                        Components.interfaces.nsISupportsWeakReference   ]),

  startup: function() // Initialize the extension
  {
      if(gBrowser)
      {
   //    gBrowser.addEventListener("DOMContentLoaded", this, false);
         gBrowser.addEventListener("pageshow", this, false);
      }

      {  // mouse move sub system
         let thenode = document.getElementById("contentAreaContextMenu");
         if(thenode)
         {
            thenode.addEventListener("popupshown",
               function(anevt)
               {
                  if(gContextMenu.onLink)
                  if(gContextMenu.target.className == "ip2newtab")
                  {
                     let thewin = gContextMenu.target.ownerDocument.defaultView;
                     if(thewin.ip2newtab) 
      thewin.ip2newtab.status.showContextMenu(anevt.currentTarget, gContextMenu.target.parentNode);
                  }
               }, false );
         }
      }

      ["close", "deactivate", "activate"].forEach(
            function(avalue) { window.addEventListener(avalue, this, false) },
               this );
   
      Services.obs.addObserver(this, "http-on-examine-response", true);
  },

   observe: function(asubject, atopic, data)
  {
      if(asubject)
      if(atopic === "http-on-examine-response")
      try {
         var thechannel = asubject.QueryInterface(Components.interfaces.nsIChannel);
         if(thechannel.loadFlags & Components.interfaces.nsIChannel.LOAD_DOCUMENT_URI)
         {
            let thadddress = thechannel.QueryInterface(Components.interfaces
                                 .nsIHttpChannelInternal).remoteAddress;
            let thehost = thechannel.URI.host.toLowerCase();
            if((thehost.length >> 1) && (thadddress))
            {
               window.setTimeout(
                     function(ahost, addr) { ip2newtab.chimera[ahost] = addr }
                        , 0, thehost, thadddress);
            }
         }
      }
      catch(err)  {
         Components.utils.reportError(err)
      }
  },

  shutdown: function()
  {
      Services.obs.removeObserver(this, "http-on-examine-response");
//      dump("_dvk_dbg_, shutdown.\n");
      if(gBrowser) gBrowser.removeEventListener("pageshow", this, false);
      iplusnewtab.monitor.reset(window);
  },

  //  "load", "unload", "pageshow"
  handleEvent: function(evt)
  {
      let thetype = evt.type;
        // load/unload the extension
      if(window === evt.currentTarget)
      {
         switch (thetype)
         {
            case "load": this.startup();
            break;
   
   //          case "DOMContentLoaded":

            case "unload": this.shutdown();
            break;
   
            case "close":
               iplusnewtab.monitor.reset(window);
               thetype = "deactivate";
            break;
   
            case "activate": iplusnewtab.monitor.verify(window);
            return;
   
            case "deactivate":
               iplusnewtab.monitor.setwin(window);
               let theready = false;
               if(gBrowser) theready = gBrowser.browsers.every(
                     function (axul) {
                        return (axul.contentDocument.readyState == "complete")
                     } );
               if(theready) ip2newtab.clearing();
            return;
         }
         window.removeEventListener(thetype, this, false);
      }
      else
      if(thetype == "pageshow")
      try {
         if(evt.target.loadOverlay)
         {
            let thedoc = evt.target;
            if(thedoc.documentURI)
            if(thedoc.defaultView.ip2newtab)
            if(thedoc.documentURI.indexOf("about:addons") === 0)
               thedoc.defaultView.ip2newtab.init(window);

         }  // top page and not xul type of doc's
         if(evt.target.defaultView === evt.target.defaultView.top)
            ip2newtab.host2cache(evt.target.baseURIObject.host, evt.timeStamp);
      }
      catch(err) {   // put out when no host
   //       Components.utils.reportError(err)
      }
  }
}  // ip2newtab.main = {
